package com.yupi.springbootinit.utils.file;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;
import java.net.MalformedURLException;

@Component
@Slf4j
public class SmbFileRead {
    @Value("${weaver.smb.userName:test}")
    private String userName;

    @Value("${weaver.smb.passWord:test}")
    private String passWord;

    private NtlmPasswordAuthentication auth;

    @PostConstruct
    private void initAuth() {
        auth = new NtlmPasswordAuthentication(null, userName, passWord);
    }

    public boolean copyFile(String source, String target) {
        return copyFile(source, target, false);
    }

    public boolean copyFile(String source, String target, boolean isCover) {
        source = source.replaceAll("\\\\", "/");
        try {
            SmbFile smbFile = new SmbFile(source, auth);
            if (smbFile.exists()) {
                File targetFile = new File(target);
                targetFile.getParentFile().mkdirs();
                if (targetFile.exists()) {
                    if (isCover) {
                        targetFile.delete();
                    } else {
                        return false;
                    }
                }
                try (InputStream inputStream = new BufferedInputStream(new SmbFileInputStream(smbFile));
                     OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile))) {

                    // 从 SMB 文件中读取内容，并写入到本地文件中
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                    log.info("File downloaded to:{} ", targetFile.getAbsolutePath());
                }
            }
        } catch (Exception e) {
            log.error("smb文件下载异常：", e);
            throw new RuntimeException("smb文件下载异常::", e);
        }
        return true;
    }

}
